from django.shortcuts import render_to_response,HttpResponseRedirect
from django.conf.urls.defaults import *
from django.contrib.auth import authenticate, login, logout
from stickurity.main.models import RegisterForm, UserProfile, LoginForm, ReportForm, UserItem
from django.template import RequestContext
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse

def SYregister(request):
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            try:
                user=User.objects.get(username=form.cleaned_data['username'])
                error = "Username already exists."
                return render_to_response('main/register.html', {'form':form,'error':error}, context_instance=RequestContext(request))
            except User.DoesNotExist:    
                newuser = User.objects.create_user(form.cleaned_data['username'],form.cleaned_data['email'],form.cleaned_data['password'])
                newuser.save()
                
                #create empty profile for new user and save to database
                newprof = UserProfile(user=newuser)
                newprof.password=form.cleaned_data['password']
                newprof.phone=request.POST['phone']
                newprof.email = request.POST['email']
                newprof.firstname = request.POST['firstname']
                newprof.lastname = request.POST['lastname']
                newprof.item_num = 0
                newprof.authority = 0
                newprof.save()
                
                form =  RegisterForm(request.POST, instance=newprof)
                userform = form.save()
                
                #Get username and password
                username=userform.username
                password = userform.password
                
                #Authenticate user and login
                user = authenticate(username=username, password=password)
                login(request,user)
                
                return HttpResponseRedirect(reverse('stickurity.main.views.SYhome'))
        else:
            return render_to_response('main/register.html',{'form':form},context_instance=RequestContext(request))
    else:
        form = RegisterForm()
        return render_to_response('main/register.html',{'form':form},context_instance=RequestContext(request))
    
def SYhome(request):
    if request.user.is_authenticated(): 
        profile = request.user.get_profile()
        if profile.authority == True:
            form = ReportForm()
            return render_to_response('main/report.html',{'form':form}, context_instance=RequestContext(request))
        else:
            return render_to_response('main/home.html',{'user':request.user})
    else:
        return HttpResponseRedirect(reverse('stickurity.main.views.SYlogin'))

def SYreport(request):
    try:
        item= UserItem.objects.get(serial=form.cleaned_data['serial'])
        
        
        error = 0
        message = "Email Succesfully Sent to the following User: "
        
        user = item.user
        
        send_mail('Your Lost Item Has Been Located!', 'The', 'darwin_quark@while-you-were.com',
    ['whileyouwerewondering@gmail.com'], fail_silently=True)
        
        return render_to_response('main/report.html', {'message':message,'error':error,'user': user}, context_instance=RequestContext(request))
    except User.DoesNotExist:    
        newuser = User.objects.create_user(form.cleaned_data['username'],form.cleaned_data['email'],form.cleaned_data['password'])
        newuser.save()
        
        #create empty profile for new user and save to database
        
    
        
  
def SYlogin(request):
    if request.user.is_authenticated(): 
        return HttpResponseRedirect(reverse('stickurity.main.views.SYhome'))
    else:
        def errorHandle(error):
            form= LoginForm()
            return render_to_response('main/login.html', { 'error': error,'form':form},context_instance=RequestContext(request))
        if request.method == 'POST':
            form = LoginForm(request.POST)
            if form.is_valid():
                username = request.POST['username']
                password = request.POST['password']
                user = authenticate(username=username,password=password)
                if user is not None:
                        if user.is_active:
                                login(request,user)
                                return HttpResponseRedirect(reverse('stickurity.main.views.SYhome'))
                        else:
                            error = u'account disabled'
                            return errorHandle(error)
                else:
                        error = u'Invalid Login. Please try again'
                        return errorHandle(error)
            else:
                error = u'form is invalid'
                return errorHandle(error)
        else:       
            form = LoginForm()
            return render_to_response('main/login.html',{'form':form},context_instance=RequestContext(request))
        
def SYlogout(request):
    logout(request)
    return HttpResponseRedirect(reverse('stickurity.main.views.SYlogin'))